package com.kcsoft.controller;

import com.kcsoft.pojo.*;
import com.kcsoft.service.TeacherService;
import com.kcsoft.service.UserService;
import com.kcsoft.utils.Md5Util;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private UserService userService;

    @PostMapping("/makeClass")
    public Result makeClass(String name){
        teacherService.makeClass(name);
        return Result.success();
    }

    @PostMapping("/delClasses")
    public Result delClasses(Integer id){
        teacherService.delClasses(id);
        return Result.success();
    }

    @PostMapping("/addStus")
    public Result addStus(@RequestBody addStus addStus){
        teacherService.addStus(addStus.getIds(), addStus.getClassId());
        return Result.success();
    }

    @PostMapping("/delStus")
    public Result delStus(@RequestBody List<Integer> ids){
        teacherService.delStus(ids);
        return Result.success();
    }

    @PostMapping("/listStus")
    public Result<PageBean<User>> listStus(Integer pageNum, Integer pageSize, Integer classId) {

        PageBean<User> pb = teacherService.listStus(pageNum, pageSize, classId);

        return Result.success(pb);

    }

    @PostMapping("/resetModel")
    public Result setModel(Integer id, Integer value) {
        teacherService.setModel(id, value);
        return Result.success();
    }

    @PostMapping("/resetPwd")
    public Result resetPwd(Integer id) {
        teacherService.resetPwd(id);
        return Result.success();
    }

    @PostMapping("/listUser")
    public Result<PageBean<User>> listUser(Integer pageNum, Integer pageSize,
                                           @RequestParam(required = false) Integer classId,
                                           @RequestParam(required = false) String stuId) {

        PageBean<User> pb = teacherService.listUser(pageNum, pageSize, classId, stuId);

        return Result.success(pb);

    }

    @GetMapping ("/listClasses")
    public Result<List<Classes>> listClasses() {

        List<Classes> cl = teacherService.listClasses();

        return Result.success(cl);

    }

    @PostMapping("/listmsg")
    public Result<PageBean<Message>> listMsg(Integer pageNum, Integer pageSize) {
        PageBean<Message> pb = teacherService.listMsg(pageNum, pageSize);
        List<Message> messages = pb.getItems();

        for (Message message : messages) {
            Integer userId = message.getCreateUser();
            User user = userService.findById(userId);
            if (user != null)
                message.setUsername(user.getUsername());
        }
        pb.setItems(messages);
        return Result.success(pb);
    }

    @PostMapping("/xlsxuser")
    public Result xlsxUser(@RequestParam("file") MultipartFile file) {
        try {
            List<User> users = parseExcel(file.getInputStream());
            if (users.isEmpty()) {
                return Result.error("文件为空或用户已存在");
            }
            teacherService.addUsers(users);
            return Result.success();
        } catch (IOException e) {
            return Result.error("文件解析错误");
        }
    }

    private List<User> parseExcel(InputStream inputStream) throws IOException {
        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        List<User> users = new ArrayList<>();
        DataFormatter formatter = new DataFormatter();

        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                continue;
            }
            User user = new User();
            user.setUsername(row.getCell(0).getStringCellValue());
            user.setName(row.getCell(0).getStringCellValue());
            Cell stuIdCell = row.getCell(1);
            if (stuIdCell.getCellType() == CellType.NUMERIC) {
                user.setStuId(formatter.formatCellValue(stuIdCell));
            } else {
                user.setStuId(stuIdCell.getStringCellValue());
            }
            Cell pwdCell = row.getCell(2);
            if (pwdCell.getCellType() == CellType.NUMERIC) {
                user.setPassword(Md5Util.genPwd(formatter.formatCellValue(pwdCell)));
            } else {
                user.setStuId(pwdCell.getStringCellValue());
            }
            User haveuser = userService.findByUsername(user.getUsername());
            if (haveuser != null) {
                continue;
            }
            users.add(user);
        }
        return users;
    }

}
